import 'dart:html';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:my_flutter_test/reqs/requests.dart';
import 'package:my_flutter_test/states/userState.dart';
import 'package:my_flutter_test/utils.dart';
import 'package:provider/provider.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  TextEditingController _pwdConfirmController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();
  Uint8List? imgBytes;
  bool registering = false;

  void _setImg(Uint8List bytes) {
    setState(() {
      imgBytes = bytes;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(24),
      child: Column(
        children: [
          ElevatedButton(
              onPressed: () => {
                    pickImage().then((value) => {_setImg(value)})
                  },
              child: const Text('选择图片')),
          Container(
            width: 360,
            height: 360,
            child: ClipOval(
              child: imgBytes == null
                  ? Image.asset('assets/img/cxk.jpg')
                  : Image.memory(imgBytes!),
            ),
          ),
          Form(
            key: _formKey, //设置globalKey，用于后面获取FormState
            autovalidateMode: AutovalidateMode.onUserInteraction,
            child: Column(
              children: <Widget>[
                TextFormField(
                  autofocus: true,
                  controller: _unameController,
                  decoration: InputDecoration(
                    labelText: "用户名",
                    hintText: "用户名或邮箱",
                    icon: Icon(Icons.person),
                  ),
                  // 校验用户名
                  validator: (v) {
                    return v!.trim().isNotEmpty ? null : "用户名不能为空";
                  },
                ),
                TextFormField(
                  controller: _pwdController,
                  decoration: InputDecoration(
                    labelText: "密码",
                    hintText: "您的登录密码",
                    icon: Icon(Icons.lock),
                  ),
                  obscureText: true,
                  //校验密码
                  validator: (v) {
                    var reg =
                        RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,15}$');
                    return reg.hasMatch(v!.trim()) ? null : "密码8-15位,包含数字字母";
                  },
                ),
                TextFormField(
                  controller: _pwdConfirmController,
                  decoration: InputDecoration(
                    labelText: "确认密码",
                    hintText: "您的登录密码",
                    icon: Icon(Icons.lock),
                  ),
                  obscureText: true,
                  //校验密码
                  validator: (v) {
                    return v!.trim() != _pwdController.text ? "两次输入密码不同" : null;
                  },
                ),
                // 登录按钮
                ChangeNotifierProvider(
                  create: (context) => UserState(),
                  child: Padding(
                    padding: const EdgeInsets.only(top: 28.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: ElevatedButton(
                            child: Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: registering
                                  ? const CircularProgressIndicator()
                                  : const Text("注册"),
                            ),
                            onPressed: () {
                              // 通过_formKey.currentState 获取FormState后，
                              // 调用validate()方法校验用户名密码是否合法，校验
                              // 通过后再提交数据。
                              if (!registering &&
                                  (_formKey.currentState as FormState)
                                      .validate()) {
                                //验证通过提交数据
                                requestRegister(_unameController.text,
                                        _pwdController.text, imgBytes)
                                    .then((_) {
                                  Navigator.pop(context);
                                }).onError((error, stackTrace) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(
                                      content: Text('注册失败！'),
                                    ),
                                  );
                                  setState(() {
                                    registering = false;
                                  });
                                });
                                setState(() {
                                  registering = true;
                                });
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
